package com.lowcodeai.auth.init;

import cn.hutool.crypto.digest.BCrypt;
import com.lowcodeai.auth.entity.UserInfo;
import com.lowcodeai.auth.mapper.UserInfoMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 数据初始化器
 * 
 * @author LowCodeAI
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DataInitializer implements CommandLineRunner {

    private final UserInfoMapper userInfoMapper;

    @Override
    public void run(String... args) throws Exception {
        initDefaultUsers();
    }

    /**
     * 初始化默认用户
     */
    private void initDefaultUsers() {
        try {
            // 检查是否已存在管理员用户
            UserInfo adminUser = userInfoMapper.selectByUsername("admin");
            if (adminUser == null) {
                // 创建管理员用户
                UserInfo userInfo = new UserInfo();
                userInfo.setUsername("admin");
                userInfo.setPassword(BCrypt.hashpw("admin123"));
                userInfo.setNickname("系统管理员");
                userInfo.setEmail("admin@lowcodeai.com");
                userInfo.setStatus(1);
                userInfo.setTenantId("default");

                userInfoMapper.insert(userInfo);
                log.info("创建默认管理员用户成功: admin");
            }

            // 检查是否已存在演示用户
            UserInfo demoUser = userInfoMapper.selectByUsername("demo");
            if (demoUser == null) {
                // 创建演示用户
                UserInfo userInfo = new UserInfo();
                userInfo.setUsername("demo");
                userInfo.setPassword(BCrypt.hashpw("demo123"));
                userInfo.setNickname("演示用户");
                userInfo.setEmail("demo@lowcodeai.com");
                userInfo.setStatus(1);
                userInfo.setTenantId("default");

                userInfoMapper.insert(userInfo);
                log.info("创建默认演示用户成功: demo");
            }

        } catch (Exception e) {
            log.error("初始化默认用户失败", e);
        }
    }
} 